<?php
	include_once("card/CardConfig.php");
	$cardState = initCardState();

	if(!empty($_GET["m"]))
	{
		if($_GET["m"]=="init")
		{
			writeSession();
			$_SESSION["userIndex"] = 0;
		}
		else if($_GET["m"]=="play")
		{
			readSession();
			if($_GET["u"] != $_SESSION["userIndex"])
			{
				echo "======= not your turn, publish a card<br/>";
			}else{
				playCard($_GET["c"],$_GET["p1"] );
				writeSession();
			}
		}
	}
	function nextPlayer()
	{
		global $cardState;
		$_SESSION["userIndex"] += $cardState->direction * $cardState->step + 8;
		$cardState->step = 1;
		$_SESSION["userIndex"] = $_SESSION["userIndex"] % 8;
		echo "======= next player=".$_SESSION["userIndex"]."<br/>";
	}
	
	function playCard($card, $para1)
	{
		global $cardState;
		
		$pc = getCard($card, $para1);
		
		echo "==   $card<br/>";
		
		if($pc->equal($cardState))
		{
			$pc->overlay($cardState);
		}else{
			echo "=======   against the rool, publish $cardState->num card and go next! <br/>";
			$cardState->num = 1;
			$cardState->type = 0;
		}
		echo "=====$cardState<br/>";
		nextPlayer();
	}
	
	
	function getCard($card, $para1)
	{
		if($card == "w4")
			return new WildDrawCard($para1);
		else if($card == "w0")
			return new WildCard($para1);
		else
		{
			$s1 = substr($card,0,1);
			$s2 = substr($card,-1);
			
			if($s2 == "d")
				return new Draw2Card($s1);
			else if($s2 == "r")
				return new ReverseCard($s1);
			else if($s2 == "s")
				return new StopCard($s1);
			else
			{
				return new NumberCard($s1,$s2);
			}
		}
	}
	
	function writeSession()
	{
		global $cardState;
		$_SESSION["color"] = $cardState->color;
		$_SESSION["no"] = $cardState->no;
		$_SESSION["num"] = $cardState->num;
		$_SESSION["direction"] = $cardState->direction;
		$_SESSION["step"] = $cardState->step;
		$_SESSION["type"] = $cardState->type;
	}
	
	function readSession()
	{
		global $cardState;
		$cardState->color = $_SESSION["color"];
		$cardState->no = $_SESSION["no"];
		$cardState->num = $_SESSION["num"];
		$cardState->direction = $_SESSION["direction"];
		$cardState->step = $_SESSION["step"];
		$cardState->type = $_SESSION["type"];
	}
	
	function initCardState()
	{
		$cardState = new CardState();
		$cardState->color = RED;
		$cardState->no = 5;
		return $cardState;
	}
?>